package com.celesea.auth.dept.service;

import com.celesea.auth.dept.dao.DeptUserDao;
import com.celesea.auth.dept.entity.DeptUser;
import com.celesea.auth.dept.vo.DeptVo;
import com.celesea.framework.service.AbstractBaseService;
import com.celesea.framework.util.CollectionKit;
import com.celesea.framework.util.Const;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.stream.Collectors;

/**
 * ${DESCRIPTION}
 *
 * @author JackYuan
 * @create 2017-10-28 20:48
 */
@Service
public class DeptUserServiceImpl extends AbstractBaseService<DeptUser> implements DeptUserService {

    @Autowired
    private DeptUserDao deptUserDao;

    @Override
    public List<DeptUser> findByDept(String deptId) {
        return deptUserDao.selectByExample(buildExample(deptId));
    }

    @Override
    public int deleteByDept(String deptId) {
        return deptUserDao.deleteByExample(buildExample(deptId));
    }

    @Override
    public int insertByDept(DeptVo entity) {
        List<DeptUser> users = Lists.newArrayList();
        List<DeptUser> members = Lists.newArrayList();
        List<DeptUser> invisibleMembers = Lists.newArrayList();
        if (CollectionKit.isNotEmpty(entity.getMembers())) {
            members = entity.getMembers().stream().map(
                    item -> generatPk(new DeptUser(entity, item, Const.Bool.TRUE))
            ).collect(Collectors.toList());
            users.addAll(members);
        }
        if (CollectionKit.isNotEmpty(entity.getInvisibleMembers())) {
            invisibleMembers = entity.getInvisibleMembers().stream().map(
                    item -> generatPk(new DeptUser(entity, item, Const.Bool.FALSE))
            ).collect(Collectors.toList());
            users.addAll(invisibleMembers);
        }
        if (CollectionKit.isNotEmpty(users)) {
            return deptUserDao.insertList(users);
        }
        return 0;
    }

    private Example buildExample(String deptId) {
        Example example = new Example(DeptUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("deptId", deptId);
        return example;
    }


}
